//
//  FindViewController.m
//  LittleFairyPoet
//
//  Created by rimi on 15/9/9.
//  Copyright (c) 2015年 周林. All rights reserved.
//

#import "DirectoryViewController.h"
#import "ZLDetailPoemViewController.h"
#import "ZLSearchViewController.h"
#import "SphereMenu.h"
#import <ReactiveCocoa.h>

static NSString *const kUITableViewCellIdentifier = @"cellIdentifier";

@interface DirectoryViewController () <UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource, SphereMenuDelegate>
@property (nonatomic, strong) UIImageView * searchImageView;
@property (nonatomic, strong) UITextField * searchTextField;
@property (nonatomic, strong) UITableView * resultTabView;
@property (nonatomic, strong) NSMutableArray * searchDataSource;
@property (nonatomic, strong) NSMutableArray * dataSource;
@property (nonatomic, strong) SphereMenu *filtMenu /**< 筛选 */;
@property (nonatomic, assign) BOOL isSearch;
- (void)initializeDataSource; /**< 初始化数据源 */
- (void)initializeUserInterface; /**< 初始化用户界面 */

@end

@implementation DirectoryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initializeDataSource];
    [self initializeUserInterface];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
}
#pragma mark - private
- (void)initializeDataSource {

    NSString * plistPath = [[NSBundle mainBundle]pathForAuxiliaryExecutable:@"绝句.plist"];
    _dataSource = [NSMutableArray arrayWithContentsOfFile:plistPath];
    _searchDataSource = [NSMutableArray arrayWithArray:_dataSource];
}
- (void)initializeUserInterface {
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.titleLable.text = @"学习";
    self.baseNavigationBar.backgroundColor = ZLColorRGBA(232, 233, 232, 1);
    CALayer *layer = [CALayer layer];
    layer.bounds = self.view.bounds;
    layer.position = self.view.center;
    layer.contents = (__bridge id)(IMAGE_CONTENT(@"目录背景.jpg")).CGImage;
    [self.view.layer addSublayer:layer];
    self.rightButton.hidden = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.view addSubview:self.searchImageView];
    [self.view addSubview:self.searchTextField];
    [self.view addSubview:self.resultTabView];
    [self.baseNavigationBar removeFromSuperview];
    self.baseNavigationBar.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.baseNavigationBar];
    [self.view addSubview:self.filtMenu];
    
}
#pragma mark - responds event
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}
- (void)respondsToSearchButton {
    if (self.searchTextField.text.length == 0) {
        _searchDataSource = nil;
        _searchDataSource = [NSMutableArray arrayWithArray:_dataSource];
        [self.resultTabView reloadData];
        return;
    }
    _searchDataSource = nil;
    _searchDataSource = [NSMutableArray new];
    [_dataSource enumerateObjectsUsingBlock:^(NSDictionary *poem, NSUInteger idx, BOOL *stop) {
        if ([poem[@"title"] containsString:self.searchTextField.text] || [poem[@"zuozhe"] containsString:self.searchTextField.text]) {
            [_searchDataSource addObject:poem];
        }
    }];
    [self.resultTabView reloadData];
}
#pragma mark - 系统协议
#pragma mark---协议UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return  _searchDataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kUITableViewCellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:kUITableViewCellIdentifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.accessoryType = UITableViewCellAccessoryNone;
    cell.textLabel.text = _searchDataSource[indexPath.row][@"title"];
    cell.textLabel.font = [UIFont fontWithName:@"KaiTi" size:18];
    NSString * detailStr = [NSString stringWithFormat:@"%@(%@)%ld",_searchDataSource[indexPath.row][@"zuozhe"], _searchDataSource[indexPath.row][@"chaodai"], indexPath.row];
    cell.detailTextLabel.text = detailStr;
    cell.detailTextLabel.font = [UIFont fontWithName:@"KaiTi" size:16];
    cell.backgroundColor = [UIColor clearColor];
    return cell;
}
#pragma mark - UITableViewDataSource
//设置每一行高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

//用户点击了某一行
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (!self.isFind) {
        ZLDetailPoemViewController * detailVC = [[ZLDetailPoemViewController alloc]init];
        detailVC.poemDic = _searchDataSource[indexPath.row];
        detailVC.poemSerialNo = indexPath.row;
        detailVC.poemArray = _searchDataSource;
        [self.view endEditing:YES];
        [self.navigationController pushViewController:detailVC animated:YES];
    } else {
        if (self.planPeoms.count > 10) {
            [self initializeAlertControllerWithMessage:@"已超过10首了呢，请不要给孩子太多压力喔"];
            return;
        }
        NSString * title = _searchDataSource[indexPath.row][@"title"];
        if (self.planPeoms.count > 0) {
            for (NSDictionary * obj in self.planPeoms) {
                if ([title isEqualToString:obj[@"title"]]) {
                    [self initAlertControllerDismissWithMessage:@"已存在"];
                    return;
                }
            }
        }
        [self.view endEditing:YES];
        [self.planPeoms addObject:_searchDataSource[indexPath.row]];
        [self initAlertControllerDismissWithMessage:@"已添加"];
        
    }
}

- (void)sphereDidSelected:(int)index {
    switch (index) {
        case 0:
        {
            NSString *juejuPath = [[NSBundle mainBundle]pathForAuxiliaryExecutable:@"绝句.plist"];
            _searchDataSource = [NSMutableArray arrayWithContentsOfFile:juejuPath];
            [self.resultTabView reloadData];
        }
            break;
        case 1:
        {
            NSString *lvShiPath = [[NSBundle mainBundle]pathForAuxiliaryExecutable:@"律诗.plist"];
            _searchDataSource = [NSMutableArray arrayWithContentsOfFile:lvShiPath];
            [self.resultTabView reloadData];
        }
            break;
        case 2:
        {
            ZLSearchViewController *searchVC = [ZLSearchViewController new];
            [self.navigationController pushViewController:searchVC animated:NO];
        }
        default:
            break;
    }
}
#pragma mark - getter
- (UITableView *)resultTabView {
    if (!_resultTabView) {
        _resultTabView = ({
            UITableView * tableview = [[UITableView alloc]initWithFrame:DHFlexibleFrame(CGRectMake(0, 55, ORIGIN_WIDTH, ORIGIN_HEIGHT-104), NO) style:UITableViewStylePlain];
            tableview.separatorColor = [UIColor clearColor];
            tableview.dataSource = self;
            tableview.delegate = self;
            tableview.tableFooterView = [UIView new];
            tableview.pagingEnabled = NO;
            tableview.backgroundColor = [UIColor clearColor];
            tableview;
        });
    }
    return _resultTabView;
}
- (NSMutableArray *)planPeoms {
    if (!_planPeoms) {
        _planPeoms = [NSMutableArray array];
    }
    return _planPeoms;
}

- (SphereMenu *)filtMenu {
    if (!_filtMenu) {
        
        _filtMenu = ({

            UIImage *startImage = IMAGE_CONTENT(@"搜索.png");
            UIImage *image1 = IMAGE_CONTENT(@"绝句.png");
            UIImage *image2 = IMAGE_CONTENT(@"律诗.png");
            UIImage *image3 = IMAGE_CONTENT(@"搜索.png");
            UIImage *image4 = IMAGE_CONTENT(@"古文.png");
            NSArray *images = @[image1, image2, image3, image4];
            SphereMenu *sphereMenu = [[SphereMenu alloc] initWithStartPoint:self.rightButton.center
                                                                 startImage:startImage
                                                              submenuImages:images radius:40 * DHFlexibleVerticalMutiplier()];
            sphereMenu.sphereDamping = 0.4;
            sphereMenu.sphereLength = 65;
            sphereMenu.angle = M_PI_4 * 0.9;
            sphereMenu.delegate = self;
            sphereMenu;
        });
    }
    return _filtMenu;
}

@end
